from pycparser import c_ast, c_generator
import sys
sys.path.extend(['.', '..'])
from c_ast_decl import *

builder = ASTBuilder()
# 定义 add 函数
with builder.function_def("add", [("int", "a"), ("int", "b")], "int"):
    # 函数体
    result_decl = builder.create_variable_decl('result', 'int', init=builder.create_binary_op('+', 'a', 'b'))
    
    builder.add_ret('result')

builder.create_function_decl('printf', 'int', [create_ptr_decl('format', 'char', quals=['const']), '...'])
# 定义 main 函数
with builder.function_def("main", [], "int"):
    call_add = builder.create_func_call('add', ['1', '2'])
    builder.add_func_call('printf', ['"Result: %d\\n"', call_add])
    
    i_decl = builder.create_variable_decl('i', 'int')
    j_decl = builder.create_variable_decl('j', 'int')

    with builder.for_loop(
        init=i_decl,  # for (int i=0; ...)
        cond=builder.create_binary_op('<', 'i', '10'),
        step=builder.create_unary_op('++', 'i')
    ):
        # 外层 for 循环体
        builder.add_func_call('printf', ['"i=%d\\n"', 'i'], )
        
        # 内层 while 循环
        with builder.while_loop(
            cond=builder.create_binary_op('!=', 'j', '5')
        ):
            builder.add_assignment('=', 'j', builder.create_binary_op('+', 'j', '1'))
            
            a_decl = builder.create_variable_decl('a', 'int')
            b_decl = builder.create_variable_decl('b', 'int')
            cond_outer = builder.create_binary_op(op='>', left='a', right='0')
            cond_inner = builder.create_binary_op(op='<', left='b', right='5')

            with builder.if_then(cond_outer):
                with builder.if_then(cond_inner):
                    stmt1 = builder.add_assignment(op='=', lvalue='a', rvalue='1')
                with builder.if_else():
                    stmt2 = builder.add_assignment(op='=', lvalue='b', rvalue='2')
                    builder.add_break()
            with builder.if_else():
                builder.add_assignment(op='=', lvalue='a', rvalue='0')
                builder.add_continue()
    builder.add_ret('0')

print(builder.generate_source())